<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from "@/utils/axios";
import { ElMessage } from "element-plus";
import { Card, Tag, Button, Image as VanImage, Icon, Empty, Swipe, SwipeItem } from 'vant';

const router = useRouter();

// 定义物品类型
interface CollectionItem {
  itemId: number;
  userId: number;
  title: string;
  description: string;
  images: string;
  price: number;
  collectCount: number;
  viewCount: number;
  tag: string;
  type: number;
  rentType: number | null;
  rentCount: number | null;
  categoryId: number;
  categories: null;
  createdAt: string;
  updatedAt: string;
  user: null;
}

const userId = ref<number | null>(null);
const collections = ref<CollectionItem[]>([]);
const searchKeyword = ref<string>('');
const activeTab = ref<number>(0);
const loading = ref<boolean>(true);

// 获取收藏物品
const getCollections = (id: number) => {
  axios.post(`/api/itemCollections/getCollectionsById/${id}`)
      .then(res => {
        if (res.code === 200) {
          collections.value = res.data;
          console.log(collections.value)
        } else {
          ElMessage({
            message: "没有收藏的物品",
            type: 'warning'
          });
        }
      })
      .catch(error => {
        ElMessage({
          message: "获取收藏失败: " + error.message,
          type: 'error'
        });
      })
      .finally(() => {
        loading.value = false;
      });
}

// 初始化用户信息
const init = () => {
  return axios.post("/api/users/getUserInfo")
      .then(res => {
        userId.value = res.data.userId;
        return res.data.userId;
      });
}

// 解析图片URL
const parseImages = (images: string): string[] => {
  try {
    return JSON.parse(images);
  } catch (e) {
    return [];
  }
}

// 解析标签
const parseTags = (tag: string): string[] => {
  if (!tag) return [];
  try {
    return JSON.parse(tag);
  } catch (e) {
    return [];
  }
}

// 获取物品类型文本
const getTypeText = (type: number): string => {
  return type === 1 ? '出售' : '出租';
}

// 获取物品类型颜色
const getTypeColor = (type: number): string => {
  return type === 1 ? 'primary' : 'warning';
}

// 取消收藏
const removeCollection = (itemId: number) => {
  axios.post(`/api/itemCollections/unCollect/${userId.value}/${itemId}`)
      .then(res => {
        if (res.code === 200) {
          collections.value = collections.value.filter(item => item.itemId !== itemId);
          ElMessage({
            message: "已取消收藏",
            type: 'success'
          });
        } else {
          ElMessage({
            message: "取消收藏失败",
            type: 'error'
          });
        }
      })
      .catch(error => {
        ElMessage({
          message: "取消收藏失败: " + error.message,
          type: 'error'
        });
      });
}

// 查看物品详情
const viewItemDetail = (itemId: number) => {
  router.push(`/item/${itemId}`);
}

// 返回上一页
const goBack = () => {
  router.go(-1);
}

// 过滤收藏物品
const filteredCollections = computed(() => {
  let result = collections.value;

  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    result = result.filter(item =>
        item.title.toLowerCase().includes(keyword) ||
        item.description.toLowerCase().includes(keyword)
    );
  }

  // 类型过滤
  if (activeTab.value === 1) {
    result = result.filter(item => item.type === 1); // 出售
  } else if (activeTab.value === 2) {
    result = result.filter(item => item.type === 2); // 出租
  }

  return result;
});

onMounted(() => {
  init().then(id => {
    getCollections(id);
  });
});
</script>

<template>
  <div class="collections-container">
    <!-- 顶部标题栏 - 添加返回按钮 -->
    <div class="header">
      <van-icon name="arrow-left" size="24" color="#333" @click="goBack" class="back-icon" />
      <van-icon name="like" size="24" color="#ee0a24" />
      <h1 class="header-title">我的收藏</h1>
      <span class="collection-count">{{ collections.length }}</span>
    </div>

    <!-- 搜索框 -->
    <div class="search-box">
      <van-search
          v-model="searchKeyword"
          placeholder="搜索收藏物品"
          shape="round"
      />
    </div>

    <!-- 类型筛选标签 -->
    <div class="filter-tabs">
      <van-tabs v-model:active="activeTab" swipeable>
        <van-tab title="全部"></van-tab>
        <van-tab title="出售"></van-tab>
        <van-tab title="出租"></van-tab>
      </van-tabs>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <van-loading type="spinner" size="24px">加载中...</van-loading>
    </div>

    <!-- 收藏物品列表 -->
    <div v-else-if="filteredCollections.length > 0" class="collections-list">
      <van-card
          v-for="item in filteredCollections"
          :key="item.itemId"
          class="collection-card"
      >
        <!-- 物品图片轮播 -->
        <template #thumb>
          <van-swipe class="item-swipe" :autoplay="3000" indicator-color="#ee0a24">
            <van-swipe-item v-for="(img, index) in parseImages(item.images)" :key="index">
              <van-image
                  :src="img"
                  fit="cover"
                  class="item-image"
              />
            </van-swipe-item>
          </van-swipe>
        </template>

        <!-- 物品标题和类型 -->
        <template #title>
          <div class="card-header">
            <div class="item-title">{{ item.title }}</div>
            <van-tag :type="getTypeColor(item.type)" plain>
              {{ getTypeText(item.type) }}
            </van-tag>
          </div>
        </template>

        <!-- 物品描述 -->
        <template #desc>
          <div class="item-description">{{ item.description }}</div>
        </template>

        <!-- 物品标签 -->
        <template #tags>
          <div class="tag-container">
            <van-tag
                v-for="(tag, index) in parseTags(item.tag)"
                :key="index"
                plain
                type="primary"
                class="tag-item"
            >
              {{ tag }}
            </van-tag>
          </div>
        </template>

        <!-- 物品价格和统计信息 -->
        <template #price>
          <div class="price-info">
            <div class="price">¥{{ item.price }}</div>
            <div class="stats">
              <span class="stat-item">
                <van-icon name="eye" /> {{ item.viewCount }}
              </span>
              <span class="stat-item">
                <van-icon name="like" /> {{ item.collectCount }}
              </span>
            </div>
          </div>
        </template>

        <!-- 操作按钮 -->
        <template #footer>
          <div class="card-footer">
            <van-button
                round
                size="small"
                type="primary"
                class="action-button"
                @click="viewItemDetail(item.itemId)"
            >
              查看详情
            </van-button>
            <van-button
                round
                size="small"
                type="danger"
                class="action-button"
                @click="removeCollection(item.itemId)"
            >
              取消收藏
            </van-button>
          </div>
        </template>
      </van-card>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <empty description="暂无收藏物品">
        <template #image>
          <van-icon name="like-o" class="empty-icon" />
        </template>
        <van-button round type="primary" class="browse-button" @click="goBack">返回</van-button>
      </empty>
    </div>
  </div>
</template>

<style scoped>
.collections-container {
  padding: 16px;
  background-color: #f7f8fa;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 0;
  position: relative;
}

.back-icon {
  margin-right: 10px;
  cursor: pointer;
}

.header-title {
  font-size: 22px;
  font-weight: 600;
  color: #333;
  margin-left: 10px;
}

.collection-count {
  background-color: #ee0a24;
  color: white;
  border-radius: 12px;
  padding: 2px 8px;
  font-size: 12px;
  margin-left: 8px;
}

.search-box {
  margin-bottom: 20px;
}

.filter-tabs {
  margin: 15px 0;
}

.loading-state {
  display: flex;
  justify-content: center;
  padding: 40px 0;
}

.collections-list {
  margin-top: 15px;
}

.collection-card {
  margin-bottom: 16px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.item-swipe {
  height: 200px;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 12px;
}

.item-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.item-title {
  font-size: 18px;
  font-weight: 600;
  flex: 1;
}

.item-description {
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
  line-height: 1.5;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  margin: 8px 0;
}

.tag-item {
  margin-right: 8px;
  margin-bottom: 8px;
}

.price-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.price {
  color: #ee0a24;
  font-weight: bold;
  font-size: 18px;
}

.stats {
  display: flex;
  color: #969799;
  font-size: 13px;
}

.stat-item {
  display: flex;
  align-items: center;
  margin-left: 12px;
}

.card-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f7f8fa;
}

.action-button {
  margin-left: 10px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.empty-icon {
  font-size: 60px;
  color: #c8c9cc;
}

.browse-button {
  margin-top: 20px;
}
</style>